<template>
  <div class="summaryChart">
    <div class="summary">
      <header>
        <div class="title">
          集团关键业务环节数字化覆盖度整体情况
          <Tooltip placement="right" transfer max-width="1200">
            <Icon type="ios-help-circle-outline" />
            <div slot="content">
              <div>
                关键业务环节数字化覆盖度：指运用5G、大数据、云计算、人工智能、物联网、区块链等新一代数字技术对企业价值链深度和广度的变革、优化和支撑情况。企业关键业务环节数字化覆盖度由广度和深度组成，一般情况下各占50%，每个产业基于不同的产业特性，在广度和深度的权重分配会略有不同。
              </div>
              <br />
              <div>
                关键业务环节数字化覆盖深度：企业管理价值链（指战略、人力、财务、办公、审计、法律等）和业务价值链（指研发、供应链、生产、物流、营销、运营等）的覆盖度。
              </div>
              <br />
              <div>
                关键业务环节数字化覆盖广度：代表智能化应用的空间区域覆盖范围，体现了智能化应用的推广情况，例如，工厂、网点、商场、门店、公司等。
              </div>
              <br />
              <div>
                关键业务环节数字化覆盖十四五目标完成率：计算方式为
                （当前覆盖度-十四五年初覆盖度）/(十四五目标覆盖度-十四五年初覆盖度）
              </div>
              <br />
              <div>关键业务环节数字化覆盖度年度提升值：当前季度覆盖率-当年一季度覆盖率</div>
            </div>
          </Tooltip>
        </div>
        <div>
          <Select
            filterable
            placeholder="请选择"
            v-model="quarter"
            style="width:120px;margin-right: 10px;"
            @on-change="changeQuarterCover"
          >
            <Option v-for="item in quarterList" :value="item.value" :key="item.value">{{ item.value }}</Option>
          </Select>
          <RPButton optType="create" type="info" text="导出" @click="handleExport" />
        </div>
      </header>
      <div class="table">
        <Table ref="table" :columns="columns" :data="tableData" height="600"></Table>
      </div>
    </div>
    <div class="promote">
      <div class="chart1">
        <header>
          <div class="title">数字化覆盖度季度提升情况</div>
          <Select filterable placeholder="请选择" v-model="bisCode" @on-change="changeBu">
            <Option v-for="item in filterBuList" :value="item.key" :key="item.key">{{ item.value }}</Option>
          </Select>
        </header>
        <div class="lineChart" style="height: 300px;">
          <promote-chart style="height: 300px;" :chartData="chartData"></promote-chart>
        </div>
      </div>
      <div class="chart2">
        <header>
          <div class="title">数字化覆盖度走势</div>
          <Select filterable placeholder="请选择" v-model="bisCode_trend" @on-change="changeBuTrend">
            <Option v-for="item in filterBuList" :value="item.key" :key="item.key">{{ item.value }}</Option>
          </Select>
        </header>
        <div style="height: 300px;">
          <trend-chart style="height: 300px;" :chartData="chartData2"></trend-chart>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { changeBuData, changeBuTrendData } from './data'
import cover2Api from '@/api/cover2'
import { saveAs } from 'file-saver'
import * as XLSX from 'xlsx'
import { columns } from './columns'
import promoteChart from './promoteChart/index.vue'
import trendChart from './trendChart/index.vue'
import { mapState } from 'vuex'
export default {
  name: 'summaryChart',
  components: {
    promoteChart,
    trendChart
  },
  data() {
    return {
      filterBuList: [],
      quarter: '',
      bisCode: '',
      bisCode_trend: '',
      bisObjs: '',
      columns: columns,
      tableData: [],
      height: '300px',
      chartData: null,
      chartData2: null,
      excludeBuCodeList: ['CRCAS', 'CRCAPM', 'CRDIGITAL', 'CRCS']
    }
  },
  props: {
    quarterList: {
      type: Array,
      default: () => []
    },
    buList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    ...mapState(['writeablePeriod']),
    buCode() {
      return this.$store.state.userBu.key
    }
  },
  mounted() {
    this.bisCode = this.buCode || this.buList[0].key
    this.bisCode_trend = this.buCode || this.buList[0].key
    this.filterBuList =
      this.buCode == 'CR' || this.buCode == 'CRC'
        ? this.buList.filter(item => item.key != 'CRC' && !this.excludeBuCodeList.includes(item.key))
        : this.buList.filter(item => item.key == 'CR' || item.key == this.buCode)
    if (this.bisCode === 'CRC') {
      //把集团总部CRC转为华润集团
      this.bisCode = 'CR'
      this.bisCode_trend = 'CR'
    }
    this.quarter = this.writeablePeriod || this.quarterList[0].value
    this.bisObjs = this.buList.reduce((res, item) => ((res[item.key] = item.value), res), {})
    this.changeQuarterCover()
    this.changeBu()
    this.changeBuTrend()
  },
  methods: {
    changeQuarterCover() {
      cover2Api
        .summary({ period: this.quarter })
        .then(data => {
          this.tableData = []
          data.data.forEach(element => {
            if (!this.excludeBuCodeList.includes(element.buCode)) {
              this.tableData.push({
                name: this.bisObjs[element.buCode],
                depth: element.depth === -1 ? '-' : (element.depth * 100).toFixed(2) + '%',
                width: element.scope === -1 ? '-' : (element.scope * 100).toFixed(2) + '%',
                cover: element.coverage === -1 ? '-' : (element.coverage * 100).toFixed(2) + '%',
                promote: element.improvement === -1 ? '-' : (element.improvement * 100).toFixed(2) + 'ppt',
                finished: element.completionRate === -1 ? '-' : (element.completionRate * 100).toFixed(2) + '%'
              })
            }
          })
        })
        .catch(() => {
          this.tableData = []
        })
    },
    changeBu() {
      cover2Api
        .improvement({ buCode: this.bisCode })
        .then(res => {
          this.chartData = { labels: [], series: [] }
          this.chartData.labels = [...changeBuData.labels]
          this.chartData.series = [...changeBuData[this.bisCode].series]
          res.data.forEach(item => {
            if ('2024-Q1' !== item.period) {
              //过滤2024-Q1的数据
              this.chartData.labels.push(item.period)
              this.chartData.series.push((item.ppt * 100).toFixed(2))
            }
          })
        })
        .catch(() => {
          this.chartData = { labels: [], series: [] }
        })
    },
    changeBuTrend() {
      cover2Api
        .trend({ buCode: this.bisCode_trend })
        .then(res => {
          this.chartData2 = {
            labels: [],
            series: [
              { label: '深度', data: [] },
              { label: '广度', data: [] },
              { label: '覆盖率', data: [] }
            ]
          }
          this.chartData2.labels = [...changeBuTrendData.labels]
          this.chartData2.series[0].data = [...changeBuTrendData[this.bisCode_trend].depth]
          this.chartData2.series[1].data = [...changeBuTrendData[this.bisCode_trend].scope]
          this.chartData2.series[2].data = [...changeBuTrendData[this.bisCode_trend].coverageRate]
          res.data.forEach(item => {
            this.chartData2.labels.push(item.period)
            this.chartData2.series[0].data.push(item.depth)
            this.chartData2.series[1].data.push(item.scope)
            this.chartData2.series[2].data.push(item.coverageRate)
          })
        })
        .catch(() => {})
    },
    prepareSheetData() {
      // 准备表头
      const headers = this.columns.map(column => column.title)
      // 准备数据，第一行是表头，其余是数据
      const data = [headers, ...this.tableData.map(row => headers.map(header => row[this.getColumnKeyByTitle(header)]))]
      return data
    },
    getColumnKeyByTitle(title) {
      // 根据表头标题找到对应的 key
      const column = this.columns.find(col => col.title === title)
      return column ? column.key : null
    },
    handleExport() {
      // 创建工作簿和工作表
      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.aoa_to_sheet(this.prepareSheetData())
      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      // 导出工作簿为 Blob 对象
      const wBlob = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      // 保存 Blob 对象为文件
      try {
        saveAs(new Blob([wBlob], { type: 'application/octet-stream' }), this.quarter + '覆盖度整体情况.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e, wBlob)
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.ivu-select {
  width: 25%;
}
.summaryChart {
  display: flex;
  margin: 20px 0;
  gap: 20px;
  .summary {
    flex: 1;
    header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      .title {
        font-size: 18px;
        font-weight: 700;
      }
    }
  }
  .promote {
    flex: 1;
    .chart1 {
      header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .title {
          font-size: 18px;
          font-weight: 700;
        }
      }
    }
    .chart2 {
      header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .title {
          font-size: 18px;
          font-weight: 700;
        }
      }
    }
  }
}
</style>
